import { App, DirectiveBinding } from "vue";

//创建元素和动画的映射
const animationMap = new WeakMap()
//进入视口才播放动画
const ob = new IntersectionObserver(entries => {
  for (const {target,isIntersecting} of entries) {
    if (isIntersecting){
      //通过元素获取对象的映射
      const animation = animationMap.get(target)
      //播放动画
      animation.play()
      //取消监听
      ob.unobserve(target)
    }
  }
})

//判断元素是否在视口之下
function isBelowViewport(el: HTMLHtmlElement) {
  const rect = el.getBoundingClientRect()
  return rect.top > window.innerHeight
}

export function slideIn(app: App){
  app.directive('slide-in',{
    mounted(el:HTMLHtmlElement,bindings: DirectiveBinding){
      //视口之上不用动画
      if (!isBelowViewport(el))return

      //动画关键帧(不影响元素的样式)
      const animation = el.animate([
        {
          transform: 'translateY(150px)',
          opacity: 0.5
        },
        {
          transform: 'translateY(0)',
          opacity: 1
        },
      ],{
        duration:800,
        easing:'ease'
      })
      //先暂停动画
      animation.pause()
      //设置元素和动画的映射
      animationMap.set(el,animation)
      //监听元素进入视口
      ob.observe(el)
    },
    unmounted(el:HTMLHtmlElement){
      ob.unobserve(el)
    }
  })
}
